﻿using Core.AdminUI.V2.Controllers.Base;
using Core.AdminUI.V2.Models.Clerk;
using Core.AdminUI.V2.Models.User;
using Core.FrameWork.Commons.ApiResult;
using Core.FrameWork.Commons.Extensions;
using Core.FrameWork.Commons.Loging;
using Core.FrameWork.Commons.Mapping;
using Core.FrameWork.Models;
using Core.FrameWork.Models.Enum.Order;
using Core.FrameWork.Models.Enum.User;
using Core.FrameWork.Models.Models.User;
using Core.FrameWork.Models.User;
using Core.FrameWork.Service.User;
using Core.FrameWork.Service.ViewBaseTree;
using Masuit.Tools.Linq;
using Masuit.Tools.Systems;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Core.AdminUI.V2.Controllers
{
    /// <summary>
    /// 后台店员管理
    /// </summary>
    public class UserClerkController : BaseController
    {
        /// <summary>
        /// 用户通用服务
        /// </summary>
        private readonly UserService _userService;
        private readonly IViewTreeConfigService _viewTreeConfigService;
        public UserClerkController(AdminContext adminContext, UserService userService, IViewTreeConfigService viewTreeConfigService) : base(adminContext)
        {
            _userService = userService;
            _viewTreeConfigService = viewTreeConfigService;
        }
        #region 视图
        /// <summary>
        /// 店员申请列表
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> ApplyIndex()
        {
            ViewBag.GroupList = await _viewTreeConfigService.GetSysBaseTreeByPid(BaseTreeConfig.UserClerkGroupId);
            ViewBag.Role = CurrentUser.Roles;
            return View();
        }
        public IActionResult ApplyUpdate(string Id = "")
        {
            if (!Guid.TryParse(Id, out var GId))
            {
                return Redirect("Index");
            }

            var changeClerkInfo = _adminContext.UserSimpleChangeClerk.FirstOrDefault(s => s.Id.Equals(GId));

            if (changeClerkInfo == null)
            {
                return Redirect("Index");
            }

            return View(changeClerkInfo);
        }

        /// <summary>
        /// 店员列表
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> Index()
        {
            ViewBag.GroupList = await _viewTreeConfigService.GetSysBaseTreeByPid(BaseTreeConfig.UserClerkGroupId);
            ViewBag.Role = CurrentUser.Roles;
            return View();
        }
        #endregion
        #region 店员申请接口
        /// <summary>
        /// 获取店员申请列表数据
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="userClerkName"></param>
        /// <param name="name"></param>
        /// <param name="weChatAccount"></param>
        /// <param name="groupId"></param>
        /// <param name="sex"></param>
        /// <param name="beginCTime"></param>
        /// <param name="endCTime"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionDescription("获取店员申请列表数据", LogResponseData = false)]
        public async Task<PageResult<RespApplyClerk>> ApplyGetPageList(int page = 1, int limit = 10, string userClerkName = "", string name = "", string weChatAccount = "", string groupId = "", int sex = 2, string beginCTime = "", string endCTime = "", ApplyClerkUser state = 0)
        {
            Expression<Func<UserSimpleChangeClerk, bool>> exp = m => true;

            if (!string.IsNullOrEmpty(userClerkName))//店员昵称
            {
                exp = exp.And(s => s.Name.Contains(userClerkName));
            }
            if (!string.IsNullOrEmpty(name))//用户昵称
            {
                exp = exp.And(s => s.UserSimple.Name.Contains(name));
            }
            if (!string.IsNullOrEmpty(weChatAccount))//微信号
            {
                exp = exp.And(s => s.WeChatAccount.Contains(weChatAccount));
            }
            if (Guid.TryParse(groupId, out var groupIdG))
            {
                exp = exp.And(s => s.GroupId.Equals(groupIdG));
            }
            if (sex != 2)//性别
            {
                exp = exp.And(s => s.Sex.Equals(sex));
            }
            if (!string.IsNullOrEmpty(beginCTime))//注册开始时间
            {
                if (DateTime.TryParse(beginCTime, out var beginCTimeD))
                {
                    exp = exp.And(s => s.CreateTime >= beginCTimeD);
                }
            }
            if (!string.IsNullOrEmpty(endCTime))//注册结束时间
            {
                if (DateTime.TryParse(endCTime, out var endCTimeD))
                {
                    exp = exp.And(s => s.CreateTime <= endCTimeD);
                }
            }
            exp = exp.And(s => s.State.Equals(state));//审核状态

            var list = _adminContext.UserSimpleChangeClerk.Include(s => s.UserSimple).Where(exp).OrderByDescending(m => m.CreateTime)
            .Skip((page - 1) * limit)
            .Take(limit).ToList();

            int count = _adminContext.UserSimpleChangeClerk.Count(exp);

            var resp = list.MapTo<UserSimpleChangeClerk, RespApplyClerk>();

            var groupList = await _viewTreeConfigService.GetSysBaseTreeByPid(BaseTreeConfig.UserClerkGroupId);

            foreach (var item in resp)
            {
                var activityInfo = list.FirstOrDefault(s => s.Id.Equals(item.Id));
                if (activityInfo != null)
                {
                    item.UserName = activityInfo.UserSimple.Name;
                    item.UserNumber = activityInfo.UserSimple.UserNumber;


                    item.GroupName = groupList.FirstOrDefault(s => s.Id.Equals(item.GroupId))?.TreeName;
                }
            }
            return ApiRespHelp.getApiDataListByPage(resp, count, page, limit);
        }
        /// <summary>
        /// 分配店员组
        /// </summary>
        /// <param name="Ids"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionDescription("分配店员组", LogResponseData = true)]
        public CommonResult ApportionGroup(string Ids, string groupId)
        {
            //权限验证 （超级管理员才可以审核）
            if (!CurrentUser.Roles.Contains("3"))
            {
                return ApiRespHelp.getError(-100, "您没有权限审核用户");
            }
            if (string.IsNullOrEmpty(Ids))
            {
                return ApiRespHelp.getError(-100, "Id不能为空");
            }
            if (Guid.TryParse(groupId, out var groupIdG))
            {
                return ApiRespHelp.getError(-100, "小组Id不能为空");
            }

            var listIds = Ids.Split(',').Select(s => Guid.Parse(s));

            var changeClerkList = _adminContext.UserSimpleChangeClerk.Where(s => listIds.Contains(s.Id)).ToList();

            foreach (var item in changeClerkList)
            {
                item.GroupId = groupIdG;
            }

            if (_adminContext.SaveChanges() == 0)
            {
                return ApiRespHelp.getError(-100, "操作失败");
            }

            return ApiRespHelp.getSuccess("操作成功");
        }
        /// <summary>
        /// 修改店员申请信息
        /// </summary>
        /// <param name="reqApplyClerk"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionDescription("修改店员申请信息", LogResponseData = true)]
        public CommonResult ApplyUpdate([FromBody] ReqApplyClerk reqApplyClerk)
        {
            var changeClerkList = _adminContext.UserSimpleChangeClerk.Find(reqApplyClerk.Id);

            if (changeClerkList == null)
            {
                return ApiRespHelp.getError(-100, "指定店员申请记录不存在");
            }
            changeClerkList.ImageUrl = reqApplyClerk.ImageUrl;
            changeClerkList.Name = reqApplyClerk.Name;
            changeClerkList.Phone = reqApplyClerk.Phone;
            changeClerkList.WeChatAccount = reqApplyClerk.WeChatAccount;
            changeClerkList.Sex = reqApplyClerk.Sex;
            changeClerkList.Birthday = reqApplyClerk.Birthday;
            changeClerkList.Constellation = reqApplyClerk.Constellation;
            changeClerkList.City = reqApplyClerk.City;
            changeClerkList.IsUndergo = reqApplyClerk.IsUndergo;
            changeClerkList.PlatformName = reqApplyClerk.PlatformName;
            changeClerkList.MaxMoney = reqApplyClerk.MaxMoney;
            changeClerkList.MaxLeaval = reqApplyClerk.MaxLeaval;
            changeClerkList.IsLeaveOffice = reqApplyClerk.IsLeaveOffice;
            changeClerkList.Tags = reqApplyClerk.Tags;
            changeClerkList.LastModifyTime = DateTime.Now;
            changeClerkList.LastModifyUserId = Guid.Parse(CurrentUser.Id);
            changeClerkList.LastModifyUserName = CurrentUser.Name;

            if (_adminContext.SaveChanges()==0)
            {
                return ApiRespHelp.getError(-100, "操作失败");
            }
            return ApiRespHelp.getSuccess("操作成功");
        }
        /// <summary>
        /// 审核店员
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ActionDescription("审核店员", LogResponseData = true)]
        public CommonResult ApplyClerkUser(string Ids, ApplyClerkUser apply)
        {
            //权限验证 （超级管理员才可以审核）
            if (!CurrentUser.Roles.Contains("3"))
            {
                return ApiRespHelp.getError(-100, "您没有权限审核用户");
            }
            if (string.IsNullOrEmpty(Ids))
            {
                return ApiRespHelp.getError(-100, "Id不能为空");
            }

            var listIds = Ids.Split(',').Select(s => Guid.Parse(s));

            var changeClerkList = _adminContext.UserSimpleChangeClerk.Where(s => listIds.Contains(s.Id)).ToList();

            if (changeClerkList.Count == 0)
            {
                return ApiRespHelp.getError(100, "未找到用户");
            }


            foreach (var changeClerk in changeClerkList)
            {
                if (changeClerk.State != Core.FrameWork.Models.Enum.User.ApplyClerkUser.Ok)//不可重复审核
                {
                    changeClerk.State = apply;
                    changeClerk.LastModifyUserId = Guid.Parse(CurrentUser.Id);
                    changeClerk.LastModifyUserName = CurrentUser.Name;
                    changeClerk.LastModifyTime = DateTime.Now;

                    if (changeClerk.State == Core.FrameWork.Models.Enum.User.ApplyClerkUser.Ok)//如果审核通过，向店员表插入数据
                    {
                        UserClerk userClerk = changeClerk.MapTo<UserSimpleChangeClerk, UserClerk>();

                        BuildUserClerkOrder(userClerk.Id);
                    }
                }
            }

            if (_adminContext.SaveChanges() == 0)
            {
                return ApiRespHelp.getError(-100, "操作失败");
            }

            return ApiRespHelp.getSuccess("操作成功");

        }
        /// <summary>
        /// 删除店员申请记录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ActionDescription("删除店员申请记录", LogResponseData = true)]
        public CommonResult Delete(string Id)
        {
            //权限验证 （超级管理员才可以删除）
            if (!CurrentUser.Roles.Contains("3"))
            {
                return ApiRespHelp.getError(-100, "您没有权限删除店员申请记录");
            }


            if (!Guid.TryParse(Id, out var GId))
            {
                return ApiRespHelp.getError(-100, "申请Id 格式错误");
            }

            var changeClerkInfo = _adminContext.UserSimple.Find(GId);

            if (changeClerkInfo == null)
            {
                return ApiRespHelp.getError(100, "未找到申请记录");
            }

            changeClerkInfo.IsDelete = 1;
            changeClerkInfo.DeleteUser = Guid.Parse(CurrentUser.Id);
            changeClerkInfo.DeleteUserName = CurrentUser.Name;
            changeClerkInfo.DeleteTime = DateTime.Now;

            if (_adminContext.SaveChanges() == 0)
            {
                return ApiRespHelp.getError(-100, "操作失败");
            }

            return ApiRespHelp.getSuccess("操作成功");

        }
        #endregion
        #region 店员接口
        /// <summary>
        /// 获取店员列表数据
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="name"></param>
        /// <param name="weChatAccount"></param>
        /// <param name="sex"></param>
        /// <param name="beginCTime"></param>
        /// <param name="endCTime"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionDescription("获取店员列表数据", LogResponseData = false)]
        public PageResult<RespClerk> GetPageList(int page = 1, int limit = 10, string name = "", string weChatAccount = "", int sex = 2, string beginCTime = "", string endCTime = "")
        {
            Expression<Func<UserClerk, bool>> exp = m => true;

            if (!string.IsNullOrEmpty(name))//用户昵称
            {
                exp = exp.And(s => s.Name.Contains(name));
            }
            if (!string.IsNullOrEmpty(weChatAccount))//微信号
            {
                exp = exp.And(s => s.WeChatAccount.Contains(weChatAccount));
            }
            if (sex != 2)//性别
            {
                exp = exp.And(s => s.Sex.Equals(sex));
            }
            if (!string.IsNullOrEmpty(beginCTime))//注册开始时间
            {
                if (DateTime.TryParse(beginCTime, out var beginCTimeD))
                {
                    exp = exp.And(s => s.CreateTime >= beginCTimeD);
                }
            }
            if (!string.IsNullOrEmpty(endCTime))//注册结束时间
            {
                if (DateTime.TryParse(endCTime, out var endCTimeD))
                {
                    exp = exp.And(s => s.CreateTime <= endCTimeD);
                }
            }

            var list = _adminContext.UserClerk.Where(exp).OrderByDescending(m => m.CreateTime)
            .Skip((page - 1) * limit)
            .Take(limit).ToList();

            int count = _adminContext.UserClerk.Count(exp);

            var resp = list.MapTo<UserClerk, RespClerk>();

            //foreach (var item in resp)
            //{
            //    item.VipName = (await _userService.GetUserClerkLevel(item.MapTo<RespClerk, UserClerk>()))?.VipName ?? "";
            //}
            return ApiRespHelp.getApiDataListByPage(resp, count, page, limit);
        }
        #endregion
        #region 申请店员Helper
        /// <summary>
        /// 生成店员类型
        /// </summary>
        /// <returns></returns>
        private List<UserClerkTakeOrderType> BuildUserClerkOrder(Guid UserClerkId)
        {
            var list = new List<UserClerkTakeOrderType>();

            var orderTypes = typeof(OrderTypeEnum).GetFields().ToList();
            orderTypes.Remove(orderTypes.FirstOrDefault());

            foreach (var item in orderTypes)
            {
                UserClerkTakeOrderType userClerkTakeOrderType = new UserClerkTakeOrderType()
                {
                    UserClerkId = UserClerkId,
                    OrderTypeEnum = Enum.Parse<OrderTypeEnum>(item.Name),
                    IsOpen = false,//默认服务关闭
                    CreateTime = DateTime.Now,
                };

                list.Add(userClerkTakeOrderType);
            }

            return list;
        }
        #endregion
    }
}

